import React from 'react'
import withRouter from '../withRouter'
import { List, InputItem, NavBar, Icon, Grid } from 'antd-mobile'
import io from 'socket.io-client'
import { connect } from 'react-redux'
import {getMsgList, sendMsg, recvMsg, readMsg} from '../../redux/chat.redux'
import { getChatId } from '../../util'

const socket = io('ws://localhost:3000')

@withRouter
@connect(
    state=> state,
    {getMsgList, sendMsg, recvMsg, readMsg}
)
class Chat extends React.Component {
    constructor(props) {
        super(props)
        this.state = { text: '', msg: []}
    }
    componentDidMount(){
        // const socket = io('ws://localhost:9093'
        //     ,{transports:['websocket','xhr-polling','jsonp-polling']})
        // socket.on('recvmsg', data => {
        //     console.log('recvmsg:', data)
        //     this.setState({msg: [...this.state.msg, data.text]})
        // })
        if(!this.props.chat.chatmsg.length) {
            this.props.getMsgList()
            this.props.recvMsg()
        }
        console.log(this.props)
        // const to = this.props.params.user
        // this.props.readMsg(to)
        this.fixCarousel()
    }
    componentWillUnmount() {
        console.log('componentWillUnmount')
        const to = this.props.params.user
        this.props.readMsg(to)
        this.fixCarousel()
    }
    fixCarousel() {
        setTimeout(t => {
            window.dispatchEvent(new Event('resize'))
        }, 0)
    }
    handleSubmit() {
        // socket.emit('sendmsg', {text: this.state.text })
        // this.setState({text: ''})
        // console.log('handleSubmit:', this.props)
        const from = this.props.user._id
        const to = this.props.params.user
        // const msg = this.props.msg
        const msg = this.state.text
        if(!msg.trim()) return
        this.props.sendMsg({from, to, msg})
        this.setState({
            text: '',
            showEmoji: false
        })
    }
    render(h) {
        // console.error(this.props)
        const emoji = `😀 😃 😄 😁 😆 😅 😂 😊 😇 🙂 🙃 😉 😌 😍 😘 😗 😙 😚 😋 😜 😝 😛 🤑 🤗 🤓
        😎 😏 😒 😞 😔 😟 😕 🙁 😣 😖 😫 😩 😤 😠 😡 😶 😐 😑 😯 😦 😧 😮 😲 😵 😳 😱 😨 😰 😢 😥 😭 😓 😪 😴 🙄
        🤔 😬 🤐 😷 🤒 🤕 😈 👿 👹 👺 💩 👻 💀 ☠️ 👽 👾 🤖 🎃 😺 😸 😹 😻 😼 😽 🙀 😿 😾 👐 🙌 👏 🙏 👍 👎 👊 ✊ 🤘 👌 👈 👉 👆 👇 ✋  🖐  🖖 👋  💪 🖕 ✍️   💅 🖖 💄 💋 👄 👅 👂 👃 👁  👀 `
        .split(' ').filter(v => v).map(v => ({text:v}))
        const userid = this.props.params.user
        const users = this.props.chat.users
        const Item = List.Item
        if(!users[userid]) {
            return null
        }
        const chatid = getChatId(userid, this.props.user._id)
        const chatmsgs = this.props.chat.chatmsg.filter(v => v.chatid === chatid)
        return (
            <div id='chat-page' style={{overflow:'auto',height:'94vh'}}>
                <NavBar mode='dark'
                        icon={<Icon type="left" />}
                        onLeftClick={()=>{
                            this.props.navigate(-1)
                        }}
                >
                    {users[userid].name}
                </NavBar>

                {chatmsgs.map(v => {
                    // console.log(v, userid)
                    const avatar = require(`../img/${users[v.from].avatar}.png`)
                    return v.from===userid?(
                        <List key={v._id}>
                            <Item thumb={avatar}
                            >{v.content}</Item>
                        {/* <p key={v._id}>对方发来的：{v.content}</p> */}
                        </List>
                    ) : (
                        <List key={v._id}>
                            <Item 
                            extra={<img src={avatar} alt='' />}
                            className='chat-me'>{v.content}</Item>
                        {/* <p key={v._id}>对方发来的：{v.content}</p> */}
                        </List>
                        // <p key={v._id}>我发来的：{v.content}</p>
                    )
                    // return <p key={v._id}>{v.content}</p>
                })}
                <div className='stick-footer'>
                    {/* <h2>chat with user:{this.props.params.user}</h2> */}
                    <List>
                        <InputItem
                            placeholder='请输入'
                            value={this.state.text}
                            onChange={v=>{
                                this.setState({text:v})
                            }}
                            extra={
                                <div>
                                    <span onClick={v=>{
                                        this.setState({'showEmoji':!this.state.showEmoji})
                                        this.fixCarousel()
                                    }} style={{marginRight:15}}>😃</span>
                                    <span onClick={()=>this.handleSubmit()}>发送</span>
                                </div>
                            }
                        ></InputItem>
                    </List>
                    {this.state.showEmoji?
                    <Grid columnNum={9} carouselMaxRow={4} isCarousel={true} data={emoji} 
                        onClick={el => {
                            this.setState({
                                text: this.state.text + el.text
                            })
                            console.log(el)
                        }}
                    />
                    :null}
                </div>
            </div>
        )
    }
}

export default Chat